﻿using log4net;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Timers;

namespace InfluxDB
{
    public partial class InfluxDB : ServiceBase
    {
        public InfluxDB()
        {
            InitializeComponent();
            Environment.CurrentDirectory = AppDomain.CurrentDomain.BaseDirectory;

            //初始化启动参数
            ProcessInfo = new ProcessStartInfo()
            {
                FileName = AppDomain.CurrentDomain.BaseDirectory + "influxd.exe",
                WorkingDirectory = AppDomain.CurrentDomain.BaseDirectory,
                Arguments = "-config influxdb.conf",
                UseShellExecute = false,
                CreateNoWindow = true,
                RedirectStandardOutput = true,
            };
            d_logger.Debug(ProcessInfo.ToString());
            checketimer = new Timer();
            checketimer.Enabled = false;
            checketimer.Interval = 1000;
            checketimer.Elapsed += checketimer_Elapsed;
        }

        protected override void OnStart(string[] args)
        {

            d_logger.InfoFormat("Command:{0}", String.Join(",", args));
            d_logger.InfoFormat("{0} 服务被启动.", DateTime.Now);
            StartProgram();
            checketimer.Enabled = true;
        }

        protected override void OnStop()
        {
            d_logger.InfoFormat("{0} 服务被停止.", DateTime.Now);
            checketimer.Enabled = false;
            if (DBPrcoess != null)
            {
                if (!DBPrcoess.HasExited)
                {
                    DBPrcoess.CloseMainWindow();
                    DBPrcoess.Kill();
                }
                DBPrcoess.Dispose();
            }
        }

        void DBPrcoess_OutputDataReceived(object sender, DataReceivedEventArgs e)
        {
            m_logger.Info(e.Data);
        }

        void checketimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            if (DBPrcoess.HasExited)
            {
                d_logger.InfoFormat("{0} InfluxDB进程意外关闭，重新启动.", DateTime.Now);
                StartProgram();
            }
        }

        /// <summary>
        /// 启动进程
        /// </summary>
        private void StartProgram()
        {
            if (DBPrcoess != null)
            {
                if (!DBPrcoess.HasExited)
                {
                    d_logger.InfoFormat("{0} 进程没有关闭，关闭后再启动.", DateTime.Now);
                    DBPrcoess.Kill();
                }
                DBPrcoess.Dispose();
                DBPrcoess = null;
            }
            d_logger.InfoFormat("{0} 准备启动InfluxDB进程.", DateTime.Now);
            DBPrcoess = Process.Start(ProcessInfo);
            d_logger.InfoFormat("{0} 启动InfluxDB进程成功 PID=[{1}].", DateTime.Now, DBPrcoess.Id);
            DBPrcoess.OutputDataReceived += DBPrcoess_OutputDataReceived;
            d_logger.InfoFormat("{0} 重定向数据流输出.", DateTime.Now);
            DBPrcoess.BeginOutputReadLine();
            d_logger.InfoFormat("{0} 启动完毕.", DateTime.Now);
        }
        private readonly ILog d_logger = LogManager.GetLogger("Debug");
        private readonly ILog m_logger = LogManager.GetLogger("InfluxDB");
        private Timer checketimer { get; set; }
        private ProcessStartInfo ProcessInfo { get; set; }
        private System.Diagnostics.Process DBPrcoess { get; set; }
    }
}
